package com.xiaoxiao.spring.web;

import com.xiaoxiao.spring.web.annotaition.Controller;
import com.xiaoxiao.spring.web.annotaition.RequestMapping;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Data
@Slf4j
public class HandlerMapping {

	private static Map<String, Handler> handlers = new ConcurrentHashMap<>();


	public static Handler getHandler(String url) {
		return handlers.get(url);
	}


	public static void addHandler(Class<?> clazz) {
		if (clazz.getAnnotation(Controller.class) != null) {
			try {
				Object target = clazz.newInstance();
				RequestMapping classMapping = clazz.getAnnotation(RequestMapping.class);
				String prefixMapping = classMapping == null ? "" : classMapping.value();
				Method[] methods = clazz.getMethods();
				//这里 的话 遍历 可以和bean的 service 一起
				for (int i = 0; i < methods.length; i++) {
					Method method = methods[i];
					RequestMapping methodMapping = method.getAnnotation(RequestMapping.class);
					if (methodMapping != null) {
						String mapping = prefixMapping + methodMapping.value();
						if (handlers.get(mapping) != null) {
							throw new RuntimeException("this mapping is already put");
						}
						Parameter[] parameters = method.getParameters();
						String[] argsName = null;
						if (parameters != null) {
							argsName = new String[parameters.length];
							for (int j = 0; j < parameters.length; j++) {
								argsName[j] = parameters[j].getName();
							}
						}
						handlers.put(mapping, new Handler(target, method, argsName));
					}
				}
			} catch (Exception e) {
				log.error("initMappingError:{}", e);
			}

		}
	}
}
